package com.dahuyou.trigger.http;

import com.dahuyou.types.util.HttpURLClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 测试另外三种授权许可类型
 * 1：资源拥有者凭据许可
 * 2：客户端许可
 * 3：隐式许可
 *
 * 简单起见，所有相关的代码均在该类中写了！！！
 */
//@RestController
@Controller
@RequestMapping("/otherThree")
public class OtherThreeAuthTypeTestController {
    private static final String oauthURl = "http://localhost:8899/authServer/exchangeAccessTokenByCode";

    @RequestMapping("/testOtherThreee")
    public String methodOne(HttpServletRequest request) {
        return "testOtherThreee";
    }

    @RequestMapping("/resourceOwnerBegin")
    public String resourceOwnerBegin(HttpServletRequest request) {
        return "resourceOwner";
    }

    @RequestMapping("/resourceOwnerClients")
    @ResponseBody
    public String resourceOwnerClients(HttpServletRequest request) {
        Map<String, String> params = new HashMap<String, String>();
        // TODO： 读取用户录入的用户名密码
        params.put("grant_type", "password");
        params.put("app_id", "APPIDTEST");
        params.put("app_secret", "APPSECRETTEST");
        params.put("name", "NAMETEST");
        params.put("username", "USERNAMETEST");
        params.put("password", "PASSWORDTEST");
        String accessToken = HttpURLClient.doPost("http://localhost:8899/otherThree/resourceOwnerServer", HttpURLClient.mapToStr(params));
        return "用户密码交换到令牌：" + accessToken;
    }

    @RequestMapping("/resourceOwnerServer")
    public void resourceOwnerServer(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("start accept post req, generate access_toen");

        String grantType = request.getParameter("grant_type");
        String appId = request.getParameter("app_id");

        String appSecret = request.getParameter("app_secret");
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if(!"APPSECRETTEST".equals(appSecret)){
            response.getWriter().write("app_secret is not available");
            return;
        }
        if(!"USERNAMETEST".equals(username)){
            response.getWriter().write("username is not available");
            return;
        }

        if(!"PASSWORDTEST".equals(password)){
            response.getWriter().write("password is not available");
            return;
        }
        String accessToken = generateAccessToken(appId,"USERTEST");//生成访问令牌access_token的值
        response.getWriter().write(accessToken);
    }

    /**
     * 生成access_token值
     * @param appId
     * @param user
     * @return
     */
    private String generateAccessToken(String appId,String user){

        String accessToken = UUID.randomUUID().toString();

        Map<String,String> map = new HashMap<String, String>();//在这一篇章我们仅作为演示用，实际这应该是一个全局数据库,并且有有效期
        map.put(accessToken,appId+"|"+user);

        return accessToken;
    }

    @RequestMapping("/clientCredentialClient")
    @ResponseBody
    public String clientCredentialClient(HttpServletRequest request) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("grant_type", "client_credentials");
        params.put("app_id", "APPIDTEST");
        params.put("app_secret", "APPSECRETTEST");
        String accessToken = HttpURLClient.doPost("http://localhost:8899/otherThree/clientCredentialServer", HttpURLClient.mapToStr(params));
        System.out.println("accessToken:" + accessToken);
        return "客户端凭证许可获取到令牌：" + accessToken;
    }

    @RequestMapping("/clientCredentialServer")
    public void clientCredentialServer(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("start accept post req, generate access_toen");

        String grantType = request.getParameter("grant_type");
        String appId = request.getParameter("app_id");

        String appSecret = request.getParameter("app_secret");
        String username = request.getParameter("username");
        String password = request.getParameter("password");

//        String appSecret = request.getParameter("app_secret");
        if (!"APPSECRETTEST".equals(appSecret)) {
            response.getWriter().write("app_secret is not available");
            return;
        }

        String accessToken = generateAccessToken(appId, "USERTEST");//生成访问令牌access_token的值

        response.getWriter().write(accessToken);

    }

    @RequestMapping("/implicitPermitClient")
    @ResponseBody
    public String implicitPermitClient(HttpServletRequest request) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("response_type", "token");//告诉授权服务直接返回access_token
        params.put("redirect_uri", "http://localhost:8080/AppServlet-ch02");
        params.put("app_id", "APPIDTEST");
        String accessToken = HttpURLClient.doPost("http://localhost:8899/otherThree/implicitPermitServer", HttpURLClient.mapToStr(params));
        System.out.println("accessToken:" + accessToken);
        return "隐式许可获取到令牌：" + accessToken;
    }

    @RequestMapping("/implicitPermitServer")
    public void implicitPermitServer(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("start accept post req, generate access_toen");

        String grantType = request.getParameter("grant_type");
        String appId = request.getParameter("app_id");

        String appSecret = request.getParameter("app_secret");
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if (!"APPIDTEST".equals(appId)) {
            response.getWriter().write("illegal appid!");
        }
        String accessToken = generateAccessToken(appId, "USERTEST");//生成访问令牌access_token的值

        response.getWriter().write(accessToken);
    }
}
